package com.game.manager
{
	import com.dusk.game.Logger;
	import com.dusk.net.AssetManager;
	import com.dusk.net.AssetType;
	import com.dusk.net.AssetUrl;
	import com.dusk.util.UtilBase;
	
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundMixer;
	import flash.media.SoundTransform;
	import flash.utils.Dictionary;
	
	public class SoundManager
	{
		
		public static var playing:String = "";
		
		public static var bgmStay:Boolean = true;
		public static var skillStay:Boolean = true;
		public static var currentVolume:int = 100;
		
		private static var _loopChannel:SoundChannel;
		private static var _soundCacheDict:Dictionary = new Dictionary();
		
		public static function playBgm(name:String):void
		{
			if (!bgmStay)
			{
				return;
			}
			if (playing == name)
			{
				return;
			}
			var snd:Sound = AssetManager.getIns().getSound(AssetUrl.getSoundAssetUrl(name));
			clearLoop();
			playing = name;
			if (!snd)
			{
				AssetManager.getIns().loadAsset(AssetUrl.getSoundAssetUrl(name), AssetType.SOUND, null, onLoadMusicBack);
				return;
			}
			_loopChannel = snd.play(0, 9999);
		}
		
		public static function playSound(name:String):void
		{
			if(!skillStay)
			{
				return;
			}
			if(_soundCacheDict[name])
			{
				(_soundCacheDict[name] as Sound).play();
				return;
			}
			var snd:Sound = AssetManager.getIns().getClassInstance(name) as Sound;
			if(!snd)
			{
				Logger.log("找不到音效: " + name);
				return;
			}
			_soundCacheDict[name] = snd;
			(_soundCacheDict[name] as Sound).play();
		}
		
		private static function onLoadMusicBack():void
		{
			var snd:Sound = AssetManager.getIns().getSound(AssetUrl.getSoundAssetUrl(playing));
			if(!snd)
			{
				Logger.log("找不到BGM: " + playing);
				return;
			}
			_loopChannel = snd.play(0, 9999);
		}
		
		public static function clearLoop():void
		{
			if (!_loopChannel)
			{
				return;
			}
			_loopChannel.stop();
			playing = "";
		}
		
		public static function setVolume(value:int = 100):void
		{
			currentVolume = value;
			SoundMixer.soundTransform = new SoundTransform(value * 0.01);
		}
		
		public static function closeSnd():void
		{
			SoundMixer.soundTransform = new SoundTransform(0);
		}
		
		public static function openSnd():void
		{
			SoundMixer.soundTransform = new SoundTransform(currentVolume / 100);
		}
		
		public static function clearAllCache():void
		{
			UtilBase.getAllKeys(_soundCacheDict).forEach(function(key:String,...a):void
			{
				Logger.log("delete key: " + key)
				delete _soundCacheDict[key];
			});
			Logger.log("====== clear sound cache ======");
		}
	}
}
